package com.example.innospace.demos.web.service.Impl;

import com.example.innospace.demos.pojo.Request.ProjectGeneralSetting;
import com.example.innospace.demos.pojo.Request.ProjectUploadRequest;
import com.example.innospace.demos.pojo.dto.ProjectPageQueryDTO;
import com.example.innospace.demos.pojo.entity.Project;
import com.example.innospace.demos.pojo.entity.ProjectFile;
import com.example.innospace.demos.pojo.entity.Student;
import com.example.innospace.demos.pojo.entity.Teacher;
import com.example.innospace.demos.pojo.enums.MessageEnum;
import com.example.innospace.demos.pojo.result.PageResult;
import com.example.innospace.demos.pojo.vo.ProjectPageVO;
import com.example.innospace.demos.pojo.vo.ProjectVO;
import com.example.innospace.demos.utils.OssUtil;
import com.example.innospace.demos.web.mapper.ProjectFileMapper;
import com.example.innospace.demos.web.mapper.ProjectMapper;
import com.example.innospace.demos.web.mapper.StudentMapper;
import com.example.innospace.demos.web.mapper.TeacherMapper;
import com.example.innospace.demos.web.service.ProjectService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.example.innospace.demos.pojo.enums.MessageEnum.CAPTAIN_HAS_PROJECT;

@Service
public class ProjectServiceImpl implements ProjectService
{   @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ProjectFileMapper projectFileMapper;

    @Autowired
    private OssUtil ossUtil;
    private MessageEnum MEMBER_HAS_PROJECT;
    private MessageEnum PROJECT_INFO_EMPTY;


    /**
     * 项目申报，先将所有的信息存储起来好吧
     *
     * @param projectUploadRequest
     * @param files
     * @return
     * @throws IOException
     */
    @Override
    @Transactional
    public MessageEnum saveProject(ProjectUploadRequest projectUploadRequest, List<MultipartFile> files) throws IOException {
        //确认所有的学生都没有项目参与

        if(projectUploadRequest.getProject().getStudentId()==null);
        else {
            String studentId1 = projectUploadRequest.getProject().getStudentId();
            Student student = studentMapper.findById(studentId1);
            if (student.getProjectid() != null) {
                return CAPTAIN_HAS_PROJECT;
            }
        }
        if(!projectUploadRequest.getStudent_ids().isEmpty())
        for( String studentId:projectUploadRequest.getStudent_ids())
        {
            Student student1=studentMapper.findById(studentId);
            if(student1.getProjectid() !=null)
                return MEMBER_HAS_PROJECT;
        }



        // 1. 验证输入数据
        if (projectUploadRequest.getProject() == null) {
           return PROJECT_INFO_EMPTY;
        }
        // 2. 保存项目基本信息
        Project project = projectUploadRequest.getProject();
        System.out.println(project);
        //// 2.1 设置项目的基本状态
        //设置项目的时间
        project.setStartTime(ProjectGeneralSetting.getDefaultStartDate());
        //设置项目结束时间
        project.setEndTime(ProjectGeneralSetting.getDefaultEndDate());
        project.setMidtermEndTime(ProjectGeneralSetting.getMidTermCheckDefaultDate());
        project.setFinalEndTime(ProjectGeneralSetting.getFinalCompletionDefaultDate());
        //设置当前为申报阶段
        project.setPhaseType("REVIEW");
        //设置项目的创建时间
        project.setCreateTime(LocalDateTime.now());
        //设置项目审报的初始时间
        project.setApplicationStartTime(LocalDateTime.now());
        //设置老师的审核状态
        project.setTeacherReviewStatus("0");
        //设置学院的审核状态
        project.setCollegeReviewStatus("0");
        //设置学校的审核状态
        project.setSchoolReviewStatus("0");
        //0为非，1 为是
        project.setBudgetStatus("0");

        // 2.2 保存项目并获取ID
        projectMapper.save(project);
        Integer projectId = projectMapper.getIdBystudentId(project.getStudentId());

        //3.验证是否老师都有可以添加的位置
        if(projectUploadRequest.getFirstTeacher()!=null)
        {
            //判断第一指导老师
            Teacher teacher=teacherMapper.findById(projectUploadRequest.getFirstTeacher());
            if(teacher.getSelectedProjectId1()==null)
            {
                teacherMapper.setProjectId1(projectUploadRequest.getFirstTeacher(),projectId);
            }
            else{
                if(teacher.getSelectedProjectId2()==null)
                {
                    teacherMapper.setProjectId2(projectUploadRequest.getFirstTeacher(),projectId);
                }
            }
        }
        if(projectUploadRequest.getSecondTeacher()!=null)
        {
            //判断第二指导老师
            Teacher teacher=teacherMapper.findById(projectUploadRequest.getSecondTeacher());
            if(teacher.getSelectedProjectId1()==null)
            {
                teacherMapper.setProjectId1(projectUploadRequest.getSecondTeacher(),projectId);
            }
            else{
                if(teacher.getSelectedProjectId2()==null)
                {
                    teacherMapper.setProjectId2(projectUploadRequest.getSecondTeacher(),projectId);
                }
            }
        }

        //3.将每个学生
        // 将队长的优先存储

        studentMapper.setProjectId(project.getStudentId(),projectId);
        if(!projectUploadRequest.getStudent_ids().isEmpty())
        for( String studentId:projectUploadRequest.getStudent_ids())
        {
            studentMapper.setProjectId(studentId,projectId);
        }
        // 5. 保存文件信息
        if (!files.isEmpty()) {
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    ProjectFile projectFile;
                    projectFile = new ProjectFile();
                    projectFile.setFileName(file.getOriginalFilename());
                    projectFile.setUpdateTime(LocalDateTime.now());
                    projectFile.setCreateTime(LocalDateTime.now());
                    projectFile.setPhaseType("REVIEW");
                    projectFile.setProjectId(projectId);
                    // 上传文件到OSS
                    try {
                        String ossPath = ossUtil.uploadFile(file);
                        projectFile.setOssPath(ossPath);
                    } catch (Exception e) {
                        throw new RuntimeException("文件上传失败: " + file.getOriginalFilename(), e);
                    }

                    // 保存文件信息到数据库
                    try {
                     projectFileMapper.save(projectFile);
                    } catch (Exception e) {
                        throw new RuntimeException("保存文件信息失败: " + file.getOriginalFilename(), e);
                    }
                }
            }
        }
        return MessageEnum.PROJECT_UPLOAD_SUCCESS;
    }
    @Override
    public boolean updateProject(Project project, List<MultipartFile> files) {
        //需要清空原本的信息，然后把新的信息存进去
        //但是对于项目是更新字段，对于文件是删除然后再添加，对于学生和老师，是将原来的先置未null，然后重新赋值
        //5.删除原本的文件
        projectMapper.updateProject(project);

        projectFileMapper.deleteByProjectId(project.getId());
        //6.重新上传文件并保存数据库
        // 5. 保存文件信息
        if (!files.isEmpty()) {
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    ProjectFile projectFile;
                    projectFile = new ProjectFile();
                    projectFile.setFileName(file.getOriginalFilename());
                    projectFile.setUpdateTime(LocalDateTime.now());
                    projectFile.setCreateTime(LocalDateTime.now());
                    projectFile.setPhaseType("REVIEW");
                    projectFile.setProjectId(project.getId());
                    // 上传文件到OSS
                    try {
                        String ossPath = ossUtil.uploadFile(file);
                        projectFile.setOssPath(ossPath);
                    } catch (Exception e) {
                        throw new RuntimeException("文件上传失败: " + file.getOriginalFilename(), e);
                    }

                    // 保存文件信息到数据库
                    try {
                        projectFileMapper.save(projectFile);
                    } catch (Exception e) {
                        throw new RuntimeException("保存文件信息失败: " + file.getOriginalFilename(), e);
                    }
                }
            }
        }
        //7.项目字段更新

        return true;
    }
    @Override
    public ProjectVO getInfoById(int id) {
        ProjectVO projectVO=new ProjectVO();
        //检查是否数据合格
        //1.获得项目基本信息
        Project project=new Project();
        project=projectMapper.getById(id);
        projectVO.setProject(project);
        //2.获得队长信息
        //2.1获得队长的id
        String studentId=project.getStudentId();
        Student student=new Student();
        student=studentMapper.findById(studentId);
        projectVO.setStudent(student);
        //3.获得成员基本信息
        List<Student> students=new ArrayList<>();
       students=studentMapper.findByprojectId(id);
        projectVO.setStudents(students);
        //4.获得各阶段文件
        //中期阶段文件
        List<String> MIDTERMfiles=new ArrayList<>();
        String MidtermPhase="MIDTERM";
        MIDTERMfiles=projectFileMapper.findByIdAndPhase(project.getId(),MidtermPhase);
        projectVO.setMIDTERMfiles(MIDTERMfiles);
        //初始基本阶段文件
        List<String>  REVIEWfiles=new ArrayList<>();
        String ReviewPhase="REVIEW";
        REVIEWfiles=projectFileMapper.findByIdAndPhase(project.getId(),ReviewPhase);
        projectVO.setMIDTERMfiles(REVIEWfiles);
        //最终阶段文件
        List<String> FINALfiles=new ArrayList<>();
        String FINALPhase="FINAL";
        FINALfiles=projectFileMapper.findByIdAndPhase(project.getId(),FINALPhase);
        projectVO.setFINALfiles(FINALfiles);
        //5.获得所有老师
        List<Teacher> teachers=new ArrayList<>();
        teachers.add(teacherMapper.findById(project.getFirstTeacher()));
        teachers.add(teacherMapper.findById(project.getSecondTeacher()));
        projectVO.setTeachers(teachers);
        return projectVO;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param projectPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(int pageNum, int pageSize, ProjectPageQueryDTO projectPageQueryDTO) {

        PageHelper.startPage(pageNum,pageSize);
        Page<ProjectPageVO> page=projectMapper.pageQuery(projectPageQueryDTO);
        long total=page.getTotal();
        List<ProjectPageVO> records=page.getResult();
        return new PageResult(total,records);
    }


    /**
     * 删除项目
     * @param projectId
     */
    @Override
    public void deleteByProjectId(Integer projectId) {
        //1.删除项目文件
        projectFileMapper.deleteByProjectId(projectId);
        //2.将所有学生的项目状态清空
        studentMapper.deleteByProject(projectId);
        //3.将所有老师的状态清空
        teacherMapper.deleteByProject1(projectId);
        teacherMapper.deleteByProject2(projectId);
        //4.将项目删除
        projectMapper.deleteById(projectId);

    }

    @Override
    public void setLevel(String level, int id) {
        projectMapper.setLevel(level,id);
    }

    @Override
    public void setUUID(String projectUUID, int id) {
        projectMapper.setUUID(projectUUID,id);
    }



    /**
     * 变更成员
     *
     * @param studentIds
     * @param studentId
     * @param id
     * @return
     */
    @Override
    public boolean updateStudents(List<String> studentIds, String studentId, int id) {
        //确保所有的新增成员都目前还没有添加项目
        int count=0;
        if(studentIds.isEmpty())
        for( String student_Id:studentIds)
        {
            if(studentMapper.getProjectId(studentId)==id||studentMapper.getProjectId(studentId)==null);
            else
            return false;

        }
        //1.原项目成员的项目状态全清空
        studentMapper.deleteByProject(id);
        //2.1获得项目
       Project project=projectMapper.getById(id);
        //3.2将队长状态补入
        if(studentId!=null)
       projectMapper.updateStudentId(studentId,id);
       //2.3清空队长状态
        //3.1将新队员的所有项目状态补充进去
        for( String student_Id:studentIds)
        studentMapper.setProjectId(student_Id,id);

        return true;
    }

    @Override
    public Project getById(int id) {
        return projectMapper.getById(id);
    }

    /**
     * 设置项目等级
     * @param id
     * @param level
     */
    @Override
    public void updateLevel(Integer id, String level) {
        projectMapper.updateLevel(id,level);
    }

    /**
     * 修改项目编号
     * @param id
     * @param projectUUID
     */
    @Override
    public void updateProjectUUID(Integer id, String projectUUID) {
        projectMapper.updateProjectUUID(id,projectUUID);
    }

    /**
     * 更新学校审核状态
     * @param projectId
     * @param isPassed
     */
    @Override
    public void updateSchoolApprovalStatus(Integer projectId, boolean isPassed) {
        projectMapper.setSchoolReviewStatus(projectId,1);
        projectMapper.updateSchoolApprovalStatus( projectId, isPassed);
    }

    /**
     * 更新学院审核状态
     * @param projectId
     * @param isPassed
     */
    @Override
    public void updateCollegeApprovalStatus(Integer projectId, boolean isPassed) {
        projectMapper.setCollegeReviewStatus(projectId,1);
        projectMapper.updateCollegeApprovalStatus( projectId, isPassed);
    }

    /**
     * 更新第一指导老师
     * @param teacherId
     * @param updaterId
     * @param id
     */
    @Override
    public void updateTeacherFirst(String teacherId, String updaterId, Integer id) {
        //1.将原指导老师负责的项目制空
        teacherMapper.setProjectId1(teacherId,null);
        //3.将新老师的项目id加上
        teacherMapper.setProjectId1(updaterId,id);
        //2.将项目的指导老师重新更新
        projectMapper.updateTeacherFirst(updaterId,id);
    }

    /**
     * 更新第二指导老师
     * @param teacherId
     * @param updaterId
     * @param id
     */
    @Override
    public void updateTeacherSecond(String teacherId, String updaterId, Integer id) {
        //1.将原指导老师负责的项目制空
        teacherMapper.setProjectId2(teacherId,null);
        //2.将项目的指导老师重新更新
        projectMapper.updateTeacherSecond(updaterId,id);
        teacherMapper.setProjectId2(updaterId,id);
    }

    @Override
    public boolean submitMidtermApplication(Integer projectId, MultipartFile file) {
        if (file == null)
            return false;
        ProjectFile projectFile = new ProjectFile();
        Project project = projectMapper.getById(projectId);
        projectFile.setFileName(file.getOriginalFilename());
        projectFile.setUpdateTime(LocalDateTime.now());
        projectFile.setCreateTime(LocalDateTime.now());
        projectFile.setPhaseType(project.getPhaseType());
        projectFile.setProjectId(projectId);
        // 上传文件到OSS
        try {
            String ossPath = ossUtil.uploadFile(file);
            projectFile.setOssPath(ossPath);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + file.getOriginalFilename(), e);
        }

        // 保存文件信息到数据库
        try {
            projectFileMapper.save((ProjectFile) projectFile);
            projectMapper.setis_midterm_application_submitted(true,projectId);
        } catch (Exception e) {
            throw new RuntimeException("保存文件信息失败: " + file.getOriginalFilename(), e);
        }
        return true;
    }

    @Override
    public void submitMidtermExtensionRequest(boolean isProjectExtended, Integer projectId) {
       projectMapper.setMidtermExtensionRequest(isProjectExtended,projectId);
    }

    @Override
    public void updatePhaseType(String phaseType, Integer projectId) {
        //更新阶段类型
        projectMapper.updatePhaseType(phaseType,projectId);
        //重置阶段状态
        projectMapper.setSchoolReviewStatus(projectId,0);
        projectMapper.setCollegeReviewStatus(projectId,0);
    }
}
